package com.juma.cartridge.retryque;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;

import lombok.extern.slf4j.Slf4j;

import com.juma.cartridge.retryque.cmd.Action;
import com.juma.cartridge.retryque.cmd.Command;

@Slf4j
public class TaskJob implements Runnable {

    private RetryHandler handler;
    
    private RetryTask task;
    
    private String scanner;
    
    private TaskLeaseProlong prolong;
    
    private BlockingQueue<Command> commandQue;
    
    public TaskJob(RetryHandler handler,RetryTask task,String scanner,TaskLeaseProlong prolong,BlockingQueue<Command> commandQue) {
        this.handler = handler;
        this.task = task;
        this.scanner = scanner;
        this.prolong = prolong;
        this.commandQue = commandQue;
    }
    
    
    
    @Override
    public void run() {
        RetryResult rr = null;
        try {
            if(handler==null) {
                rr = RetryResult.RETRY;
                task.setDetail("No RetryHandler Found");
            } else {
                rr = handler.retry(task);    
            }
        }catch(Exception e) {
            task.setDetail(e.getMessage());
            rr = RetryResult.RETRY;
        }
        
        try {
            //任务结束,直接删除任务
            if(rr==RetryResult.OVER) {
//                retryQueueDao.delete(free);
                commandQue.put(createCommand(Action.DELETE));
                return;
            }
            
            task.setStatus(rr.getTaskStatus());
            if(task.isRefresh()) {
//                retryQueueDao.update(task);
                commandQue.put(createCommand(Action.UPDATE));
            }
            
            //如果是挂起状态,则设定挂起时长(挂起的任务不进行释放,挂起超时之后会自动被扫描并重置为retry状态)
            if(rr==RetryResult.DELAY) {
//                TaskLeaseProlong tlp = buildProlong();
//                retryQueueDao.prolongLock(tlp);
                commandQue.put(createCommand(Action.PROLONG));
                return;
            }
            
            //逻辑走到这里,说明任务置为RETRY或BROKEN,则需求进行释放
//            retryQueueDao.release(free);
            commandQue.put(createCommand(Action.RELEASE));
        }catch(Exception e){
            log.error("更新/释放任务异常:"+e.getMessage(),e);
        }finally{
            prolong.removeId(task.getId());
        }
    }

    private Command createCommand(Action action) {
        List<RetryTask> tasks = new ArrayList<RetryTask>(1);
        tasks.add(task);
        Command cmd = new Command(action,scanner,prolong,tasks);
        return cmd;
    }
    
}
